﻿using System;
using System.Linq;
using Cartographer.Builder;

namespace Cartographer.Generator
{
	public static class WorldGenerator
	{
		public static float[,] GenerateHeightMap(int width, int height, int octaves, float frequency, float amplitude, int seed)
		{
			var data = new float[width * height];
			var min = float.MaxValue;
			var max = float.MinValue;

			Noise2D.SetSeed(seed);

			for (var octave = 0; octave < octaves; octave++)
			{
				for (var offset = 0; offset < width * height; offset++)
				{
					var i = offset % width;
					var j = offset / width;
					var noise = Noise2D.Noise(i * frequency * 1f / width, j * frequency * 1f / height);
					noise = data[j * width + i] += noise * amplitude;
					min = Math.Min(min, noise);
					max = Math.Max(max, noise);
				}
				frequency *= 2;
				amplitude /= 2;
			}

			var heights = data.Select(f => (f - min)/(max - min)).ToArray();
			var output = new float[width, height];
			for (var offset = 0; offset < width * height; offset++)
			{
				var x = offset % width;
				var y = offset / width;
				output[x, y] = heights[offset];
			}

			return output;
		}
	}
}